<template>
    <el-dialog :title="title" :visible.sync="visible" width="560px" append-to-body :close-on-click-modal="false">
        <BaseForm2
            ref="form"
            v-loading="loading"
            label-position="right"
            label-width="114px"
            :fields="fields"
            :text-model="textModel"
            :data="form"
            size="medium"
            @updateValue="updateEvent"
        ></BaseForm2>
        <div slot="footer" class="dialog-footer">
            <BaseButton :loading="submitLoading" @click="submitForm">保 存</BaseButton>
            <BaseButton type="recond" @click="cancel">取 消</BaseButton>
        </div>
    </el-dialog>
</template>

<script>
import BaseForm2 from '@/components/BaseForm2'
import {
    DecisionItemModel,
    LineHighwayModel,
    ManagementOfficeModel,
    MaintSchemeModel,
    RoadConditionsModel,
    PerformancePredictionModel,
    PriorityOrderingModel
} from '@/models'

export default {
    name: 'AddOrUpdate',
    components: {
        BaseForm2
    },
    data() {
        return {
            model: new DecisionItemModel(),
            lineHighwayModel: new LineHighwayModel(),
            managementOfficeModel: new ManagementOfficeModel(),
            schemeModel: new MaintSchemeModel(),
            roadConditionsModel: new RoadConditionsModel(),
            performancePredictionModel: new PerformancePredictionModel(),
            priorityOrderingModel: new PriorityOrderingModel(),
            title: '新增决策项目',
            visible: false,
            submitLoading: false,
            loading: false,
            // 表单参数
            form: {},
            type: 'add',
            id: '',
            textModel: false,
            fields: [
                {
                    label: '',
                    children: [
                        {
                            options: [],
                            key: 'orgName',
                            valueKey: 'label',
                            label: '管养单位',
                            type: 'normal-select',
                            span: 24,
                            filterable: true,
                            rules: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }]
                        },
                        {
                            options: [],
                            key: 'highwayCode',
                            label: '路段名称',
                            type: 'normal-select',
                            span: 24
                        },
                        {
                            key: 'roadSectionDetail',
                            type: 'input',
                            label: '路段详细说明',
                            span: 24
                        },
                        {
                            key: 'decisionItemName',
                            type: 'input',
                            label: '决策项目名称',
                            span: 24,
                            maxlength: '30',
                            'show-word-limit': true,
                            rules: [
                                { required: true, message: '必填项', trigger: ['blur'] },
                                { validator: this.validUnique, trigger: ['blur'] }
                            ]
                        },
                        {
                            options: [],
                            key: 'standardId',
                            label: '所属模型',
                            type: 'normal-select',
                            span: 24,
                            placeholder: '选择维修后路况标准',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            options: [],
                            key: 'performancePredictionModelId',
                            label: '',
                            type: 'normal-select',
                            span: 24,
                            placeholder: '选择性能预测模型',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            options: [],
                            key: 'prioritizationModelId',
                            label: '',
                            type: 'normal-select',
                            span: 24,
                            placeholder: '选择优先排序模型',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            options: [],
                            key: 'maintSchemeId',
                            label: '养护方案',
                            type: 'normal-select',
                            span: 24,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            key: 'remark',
                            type: 'textarea',
                            label: '备注',
                            maxlength: '200',
                            'show-word-limit': true,
                            span: 24
                        }
                    ]
                }
            ]
        }
    },
    created() {
        this.getHighwayList()
        this.getManagementOfficeList()
        this.getRoadConditionsOptions()
        this.getPerformancePredictionOptions()
        this.getPriorityOrderingModelOptions()
        this.getSchemeOptions()
    },
    methods: {
        updateEvent(data) {
            if (data.highwayCode) {
                const { label } = this.fields[0].children[1].options.find((item) => item.value === data.highwayCode) || {}
                console.log(label)
                this.form.highwayName = label
            }
            if (data.standardId) {
                const { label } = this.fields[0].children[4].options.find((item) => item.value === data.standardId) || {}
                this.form.standardName = label
            }
            if (data.performancePredictionModelId) {
                const { label } = this.fields[0].children[5].options.find((item) => item.value === data.performancePredictionModelId) || {}
                this.form.performancePredictionModelName = label
            }
            if (data.prioritizationModelId) {
                const { label } = this.fields[0].children[6].options.find((item) => item.value === data.prioritizationModelId) || {}
                this.form.prioritizationModelName = label
            }
            if (data.maintSchemeId) {
                const { label } = this.fields[0].children[7].options.find((item) => item.value === data.maintSchemeId) || {}
                this.form.maintSchemeName = label
            }
        },
        // 养护方案列表
        getSchemeOptions() {
            this.schemeModel.getList({}, { pageSize: 10000 }).then((res) => {
                const list = (res.list || []).map((item) => {
                    return {
                        value: item.id,
                        label: item.schemeName
                    }
                })
                this.$set(this.fields[0].children[7], 'options', list)
            })
        },
        getRoadConditionsOptions() {
            this.roadConditionsModel.getList({}, { pageSize: 10000 }).then((res) => {
                const list = (res.list || []).map((item) => {
                    return {
                        value: item.id,
                        label: item.modelName
                    }
                })
                this.$set(this.fields[0].children[4], 'options', list)
            })
        },
        getPerformancePredictionOptions() {
            this.performancePredictionModel.getList({}, { pageSize: 10000 }).then((res) => {
                const list = (res.list || []).map((item) => {
                    return {
                        value: item.id,
                        label: item.modelName
                    }
                })
                this.$set(this.fields[0].children[5], 'options', list)
            })
        },
        getPriorityOrderingModelOptions() {
            this.priorityOrderingModel.getList({}, { pageSize: 10000 }).then((res) => {
                const list = (res.list || []).map((item) => {
                    return {
                        value: item.id,
                        label: item.modelName
                    }
                })
                this.$set(this.fields[0].children[6], 'options', list)
            })
        },
        getOptions4() {
            const list = [
                {
                    value: 1,
                    label: '典型养护方案'
                }
            ]
            this.$set(this.fields[0].children[7], 'options', list)
        },
        getHighwayList() {
            this.lineHighwayModel.getList({}, { pageNo: 1, pageSize: 10000 }).then((res) => {
                const list = (res.list || []).map((item) => {
                    return {
                        label: item.name + '/' + item.code,
                        value: item.code
                    }
                })
                list.length > 0 && this.$set(this.fields[0].children[1], 'options', list)
            })
        },
        // 获取管理处列表，作为下拉选项
        getManagementOfficeList() {
            this.managementOfficeModel.getList({}, { pageNo: 1, pageSize: 10000 }).then((res) => {
                const list = (res.list || []).map((item) => {
                    return {
                        value: item.id,
                        label: item.name
                    }
                })
                list.length > 0 && this.$set(this.fields[0].children[0], 'options', list)
            })
        },
        // 取消按钮
        cancel() {
            this.visible = false
            this.reset()
        },
        async open(options = {}) {
            const { type, id = null } = options
            this.id = id
            this.visible = true
            this.reset()
            if (type === 'add') {
                this.title = '新增决策项目'
            } else {
                this.title = '修改决策项目'
                this.form = await this.getDetail()
            }
        },
        getDetail() {
            this.loading = true
            return this.model.detail({ id: this.id }).finally(() => {
                this.loading = false
            })
        },
        // 表单重置
        reset() {
            this.$nextTick(() => {
                this.$refs['form'].resetFields()
            })
        },
        submitForm() {
            this.$refs['form'].validate((valid, res) => {
                if (valid) {
                    console.log(res)
                    this.submitLoading = true
                    const data = {
                        ...res,
                        standardName: this.form.standardName,
                        performancePredictionModelName: this.form.performancePredictionModelName,
                        prioritizationModelName: this.form.prioritizationModelName,
                        maintSchemeName: this.form.maintSchemeName,
                        highwayName: this.form.highwayName
                    }
                    console.log(data)
                    this.id && (data.id = this.id)
                    this.model
                        .saveOrUpdate(data)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '操作成功！',
                                duration: 500,
                                onClose: () => {
                                    this.visible = false
                                    this.$emit('success')
                                }
                            })
                        })
                        .finally(() => {
                            this.submitLoading = false
                        })
                } else {
                    this.$message.error('校验失败！')
                }
            })
        },
        validUnique(rule, value, callback) {
            this.model.uniqueCheck({ decisionItemName: value, id: this.id || null }).then((res) => {
                if (res) {
                    callback(new Error('该名称已存在'))
                } else {
                    callback()
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.w-300 {
    width: 300px;
}
</style>
